import axios from 'axios';
import { ref } from 'vue';
import { defineStore } from 'pinia';

interface User {
  id: number;
  username: string;
  email: string;
  is_active: boolean;
}

interface LoginData {
  username: string;
  password: string;
}

interface RegisterData extends LoginData {
  email: string;
}

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null);
  const token = ref<string | null>(null);

  // 从localStorage恢复状态
  const initializeAuth = () => {
    const savedToken = localStorage.getItem('token');
    if (savedToken) {
      token.value = savedToken;
      fetchUserInfo();
    }
  };

  // 注册
  const register = async (data: RegisterData) => {
    try {
      const response = await axios.post('/api/auth/register', data);
      return response.data;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '注册失败');
    }
  };

  // 登录
  const login = async (data: LoginData) => {
    try {
      const response = await axios.post('/api/auth/login', data);
      const { token: newToken, user: userData } = response.data;
      token.value = newToken;
      user.value = userData;
      localStorage.setItem('token', newToken);
      // 设置全局请求头
      axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`;
      return response.data;
    } catch (error: any) {
      throw new Error(error.response?.data?.message || '登录失败');
    }
  };

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const response = await axios.get('/api/auth/me');
      user.value = response.data;
    } catch (error) {
      logout();
    }
  };

  // 登出
  const logout = () => {
    user.value = null;
    token.value = null;
    localStorage.removeItem('token');
    delete axios.defaults.headers.common['Authorization'];
  };

  return {
    user,
    token,
    register,
    login,
    logout,
    initializeAuth,
    fetchUserInfo
  };
});